// pages/giftCard/myGiftCard.js
let filter = require('../../utils/filter.js');
import util from '../../utils/util.js'
let app = getApp()
var requests = require('../../requests/api.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    screenHeight: wx.getSystemInfoSync().windowHeight - 50,
    prompt: {
      hidden: !0,
      icon: '../../assets/coupons/default-coupons.png',
      title: '目前还没有绑定礼品卡哦~',
    },
    usePrompt: {
      hidden: !0,
      icon: '../../assets/coupons/default-coupons.png',
      title: '暂无使用记录~',
    },

    //没有更多
    loading: true, //加载框是否显示
    searchLoading: false, //把"上拉加载"的变量设为true，显示  
    searchLoadingComplete: false, //把“没有数据”设为false，隐藏  
    giftCardArray: [

    ],
    page: 1,
    pageSize: 10,
    //激活礼品卡
    activateMsg: "",
    //礼品卡激活码
    giftCardNo: "",
    //使用记录
    showModalStatus: false,
    animationData: "",
    //礼品卡激活结果
    resultMsg: "",
    //礼品卡使用记录
    giftCardUseList: [],
    giftCardCode: "",
    //长度中转站
    cardlen: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    new app.WeToast();

  },

  //NET
  request_giftCards: function(page) {
    //网络请求的时候先把加载框加出来
    const self = this;
    self.setData({
      loading: false,
    });
    var params = {
      currentPage: page,
      pageSize: this.data.pageSize
    };

    self.my_giftCards(params)


  },
  onShow: function() {
    this.setData({
      page: 1, //分页从第一页开始加载
      giftCardArray: [], //初始化商品数组
      searchLoading: true, //把"上拉加载"的变量设为true，显示  
      searchLoadingComplete: false //把“没有数据”设为false，隐藏  
    });
    this.request_giftCards(this.data.page); //加载产品列表数据
  },
  //我的礼品卡列表
  my_giftCards: function(params) {
    const self = this;

    requests.getGiftCardWithbalance(params, (res) => {
      console.log(res.data)
      if (res.data.giftCardList.length == 0) { //没有数据
        self.setData({
          searchLoadingComplete: true, //把“没有数据”设为true，显示

        })
      } else { //说明还有数据
        self.setData({
          searchLoadingComplete: false, //把“没有数据”设为false，隐藏  

        })
      };
      var giftCardArr = self.data.giftCardArray;
      console.log(res.data)
      if (params.currentPage == 1) {
        giftCardArr = res.data.giftCardList;
      } else {
        giftCardArr = giftCardArr.concat(res.data.giftCardList);
      }

      self.setData({
        loading: true, //隐藏加载框
        giftCardArray: giftCardArr, //给数组赋值，
        'prompt.hidden': giftCardArr.length,

      })

    }, (data) => {
      self.setData({
        searchLoadingComplete: true, //把“没有数据”设为true，显示
        loading: true, //隐藏加载框
        'prompt.hidden': giftCardArr.length,

      })
      if (util.alertNetworkError(data)) {
        self.wetoast.toast({
          title: data.resMsg,
        })
      }

    }, () => {
      self.setData({
        searchLoading: false //把"上拉加载"的变量设为false，隐藏  

      })
    });
  },

  //上拉触底
  moreData: function() {
    let that = this;
    //如果还有数据就继续加载
    if (!that.data.searchLoading && !that.data.searchLoadingComplete) {
      that.setData({
        page: that.data.page + 1
      })
      that.setData({
        searchLoading: true //把"上拉加载"的变量设为false，隐藏

      })
      that.request_giftCards(that.data.page)

    }
  },

  /**
   * 当页面滑动到底部时触发的方法,删掉这个方法后控制台会报事件警告
   */
  onReachBottom: function() {},

  /**
   * 购买新卡
   */
  buyGiftCard: function() {

    wx.navigateTo({
      url: '../giftCard/giftCardProduct',
    })
  },

  /**
   * 弹窗
   */
  showDialogBtn: function() {

    this.setData({
      showModal: true
    })
  },
  /**
   * 弹出框蒙层截断touchmove事件
   */
  preventTouchMove: function() {},
  /**
   * 隐藏模态对话框
   */
  hideDialogModal: function() {
    this.setData({
      showModal: false,
      giftCardNo: "",
      activateMsg: ""
    });
  },
  hideResultModal: function() {
    this.setData({
      showResultModal: false,
    })
  },

  /**
   * 对话框确认按钮点击事件
   */
  onConfirm: function() {
    let that = this;
    if (that.data.giftCardNo == "") {
      that.setData({
        activateMsg: "请输入密码"
      })
      return
    }
    if (that.data.giftCardNo.length < 16) {
      that.setData({
        activateMsg: "请输入正确的礼品卡密码"
      })
      return
    }

    that.setData({
      activateMsg: "",
    })
    that.requestActivateGiftCard()

  },
  //使用记录
  useLogClick: function(event) {
    console.log(event)
    var giftCardId = event.currentTarget.dataset.giftcardid;
    var giftCardCode = event.currentTarget.dataset.giftcardcode;
    this.requestGiftCardUselog(giftCardCode, giftCardId)

  },
  //激活礼品卡
  requestActivateGiftCard: function() {
    const that = this
    var params = {
      giftCardPwd: this.data.giftCardNo
    };
    wx.showLoading({
      title: '',
    })
    requests.activateGiftCard(params, (res) => {
      wx.hideLoading()
      console.log(res.data)
      this.setData({
        showResultModal: true,
        showModal: false,
        resultMsg: "礼品卡激活成功",
        giftCardNo: ""
      })
      this.request_giftCards(1)

    }, (error) => {
      wx.hideLoading()
      if (error.resCode == 40510) {
        this.setData({
          showResultModal: true,
          showModal: false,
          resultMsg: error.resMsg,
          giftCardNo: ""
        })
      } else {
        if (util.alertNetworkError(error)) {
          that.wetoast.toast({
            title: error.resMsg,
          })
        }
        this.setData({
          activateMsg: error.resMsg
        })
      }


    }, () => {

    });
  },
  //获取礼品卡使用记录
  requestGiftCardUselog: function(giftCardCode, giftCardId) {
    const that = this
    var params = {
      giftCardId: giftCardId
    };
    requests.getGiftCardUselog(params, (res) => {
      console.log(res.data)
      this.setData({
        "giftCardUseList": res.data.giftCardUseList,
        "giftCardCode": giftCardCode
      })
      this.showModal()
    }, (error) => {
      if (util.alertNetworkError(error)) {
        that.wetoast.toast({
          title: error.resMsg,
        })
      }
      console.log(error)
    }, () => {

    });
  },
  /**
   * 礼品卡激活码
   */
  inputChange: function(e) {

    var card = e.detail.value.toUpperCase();
    var len = card.length
    //判断用户是输入还是回删
    if (len > this.data.cardlen) {
      //用户输入
      card = card.replace(/\s/g, '').replace(/(.{4})/g, "$1 ")

    } else {
      //用户回删
      card = card.replace(/(^\s*)|(\s*$)/g, "")
    }
    //将处理后的值赋予到输入框
    this.setData({
      giftCardNo: card.replace(/\s+/g, '')
    })
    //将每次用户输入的卡号长度赋予到长度中转站
    this.setData({
      cardlen: len
    })
    return card

  },
  //使用记录弹窗
  showModal: function() {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function() {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 100)
  },
  hideModal: function() {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(200).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function() {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 100)
  }

})